<!--付款单-->
<template>
  <div class="payment-order">
   
    <!-- 筛选区域 -->
    <div class="controls-section">
      <div class="filters">
        <div class="filter-item">
          <button class="btn-primary" @click="openCreate">新建</button>
          <label>关键词</label>
          <input type="text" placeholder="请输入付款单号/销售单号" v-model="query.keyword">
        </div>
        <div class="filter-item">
          <label>付款状态</label>
          <select v-model="query.paymentStatus">
            <option :value="null">全部</option>
            <option :value="0">待核销</option>
            <option :value="1">部分核销</option>
            <option :value="2">全部核销</option>
          </select>
        </div>

      </div>
      <div class="actions">
        <button class="btn-primary" @click="loadData">搜索</button>
        <button class="btn-secondary" @click="resetQuery">重置</button>
      </div>
    </div>

    <!-- 表格区域 -->
    <div class="table-section">
      <table>
        <thead>
          <tr>
            <th><input type="checkbox" v-model="selectAll" @change="toggleSelectAll"></th>
            <th>付款单号</th>
            <th class="sortable-header">
              付款状态
            </th>
            <th>付款类型</th>
            <th>客户</th>
            <th>关联销售单</th>
            <th>应付总额</th>
            <th>已核销金额</th>
            <th>待核销金额</th>
            <th>财务人员</th>
            <th>创建日期</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(item, index) in tableData" :key="index">
            <td><input type="checkbox" v-model="item.selected" @change="updateSelectAll"></td>
            <td class="link-style" @click="viewDetail(item)">{{ item.paymentOrderNo || '-' }}</td>
            <td><span :class="statusClass(fmtStatus(item.paymentStatus))">{{ fmtStatus(item.paymentStatus) }}</span></td>
            <td>{{ fmtPaymentType(item.paymentType) }}</td>
            <td class="link-style">{{ item.customerName || item.customerId || '-' }}</td>
            <td class="link-style">{{ item.relatedSalesOrder || '-' }}</td>
            <td>{{ fmtMoney(item.payableAmount) }}</td>
            <td>{{ fmtMoney(item.writtenOffAmount) }}</td>
            <td>{{ fmtMoney(item.toBeWrittenOffAmount) }}</td>
            <td>{{ item.financeUserName || item.uId || '-' }}</td>
            <td>{{ fmtDateTime(item.creationDate) }}</td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 详情抽屉 -->
    <div class="detail-drawer" :class="{ 'show': showDetailDrawer }">
      <div class="drawer-header">
        <h3>付款单详情</h3>
        <button class="close-btn" @click="closeDetailDrawer">×</button>
      </div>
      <div class="drawer-content" v-if="currentOrder">
        <div class="detail-section">
          <h4>基本信息</h4>
          <div class="detail-grid">
            <div class="detail-item">
              <label>付款单号：</label>
              <span>{{ currentOrder.paymentOrderNo }}</span>
            </div>
            <div class="detail-item">
              <label>付款状态：</label>
              <span :class="statusClass(fmtStatus(currentOrder.paymentStatus))">{{ fmtStatus(currentOrder.paymentStatus) }}</span>
            </div>
            <div class="detail-item">
              <label>客户：</label>
              <span>{{ currentOrder.customerName || currentOrder.customerId }}</span>
            </div>
            <div class="detail-item">
              <label>关联销售单：</label>
              <span>{{ currentOrder.relatedSalesOrder }}</span>
            </div>
          </div>
        </div>

        <div class="detail-section">
          <h4>金额信息</h4>
          <div class="detail-grid">
            <div class="detail-item">
              <label>应付总额：</label>
              <span class="amount">{{ fmtMoney(currentOrder.payableAmount) }}</span>
            </div>
            <div class="detail-item">
              <label>已核销金额：</label>
              <span class="amount">{{ fmtMoney(currentOrder.writtenOffAmount) }}</span>
            </div>
            <div class="detail-item">
              <label>待核销金额：</label>
              <span class="amount">{{ fmtMoney(currentOrder.toBeWrittenOffAmount) }}</span>
            </div>
          </div>
        </div>

        <div class="detail-section">
          <h4>其他信息</h4>
          <div class="detail-grid">
            <div class="detail-item">
              <label>财务人员：</label>
              <span>{{ currentOrder.financeUserName || currentOrder.uId || '-' }}</span>
            </div>
            <div class="detail-item">
              <label>创建日期：</label>
              <span>{{ fmtDateTime(currentOrder.creationDate) }}</span>
            </div>
            <div class="detail-item">
              <label>付款类型：</label>
              <span>{{ fmtPaymentType(currentOrder.paymentType) }}</span>
            </div>
          </div>
        </div>

        <div class="drawer-actions">
          <button class="btn-secondary" @click="closeDetailDrawer">取消</button>
        </div>
      </div>
    </div>

    <!-- 底部区域 -->
    <div class="footer-section">
      <div class="footer-left">
        <input type="checkbox" v-model="selectAll" @change="toggleSelectAll">
        <label>全选</label>
        <button class="btn-secondary">导出</button>
      </div>
      <div class="pagination">
        <button @click="prevPage" :disabled="pagination.current === 1">&lt;</button>
        <span class="page-indicator">{{ pagination.current }} / {{ totalPages }} 页</span>
        <button @click="nextPage" :disabled="pagination.current === totalPages">&gt;</button>
        <select v-model.number="pagination.size" @change="onPageSizeChange">
          <option value="5">5条/页</option>
          <option value="10">10条/页</option>
          <option value="20">20条/页</option>
        </select>
      </div>
    </div>

    <!-- 新建付款单弹窗 -->
    <div class="modal-overlay" v-if="createVisible" @click="createVisible=false">
      <div class="create-modal" @click.stop>
        <div class="modal-header">
          <h3>新建付款单</h3>
          <button class="close-btn" @click="createVisible=false">×</button>
        </div>
        <div class="modal-content">
          <form @submit.prevent="submitCreate">
            <div class="form-grid">
              <div class="form-group">
                <label>付款单号</label>
                <input v-model="createForm.paymentOrderNo" placeholder="自动生成，可留空" />
              </div>
              <div class="form-group">
                <label>付款状态</label>
                <select v-model.number="createForm.paymentStatus">
                  <option :value="0">待核销</option>
                  <option :value="1">部分核销</option>
                  <option :value="2">全部核销</option>
                </select>
              </div>
              <div class="form-group">
                <label>付款类型</label>
                <select v-model="createForm.paymentType">
                  <option value="0">委外付款</option>
                  <option value="1">采购付款</option>
                  <option value="2">其他付款</option>
                </select>
              </div>
              <div class="form-group">
                <label>客户ID</label>
                <input type="number" v-model="createForm.customerId" placeholder="请输入客户ID" />
              </div>
              <div class="form-group">
                <label>关联销售单</label>
                <input v-model="createForm.relatedSalesOrder" placeholder="请输入销售单号" />
              </div>
              <div class="form-group">
                <label>应付总额</label>
                <input type="number" step="0.01" v-model="createForm.payableAmount" placeholder="请输入应付总额" />
              </div>
              <div class="form-group">
                <label>已核销金额</label>
                <input type="number" step="0.01" v-model="createForm.writtenOffAmount" placeholder="请输入已核销金额" />
              </div>
              <div class="form-group">
                <label>财务人员ID</label>
                <input type="number" v-model="createForm.uId" placeholder="请输入财务人员ID" />
              </div>
            </div>
            <div class="form-actions">
              <button type="button" class="btn-secondary" @click="createVisible=false">取消</button>
              <button type="submit" class="btn-primary" :disabled="submitting">{{ submitting ? '保存中...' : '保存' }}</button>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { paymentOrderPage, paymentOrderCreate, paymentOrderDetail } from '@/api/finance/paymentOrder'

export default {
  name: 'PaymentOrder',
  data() {
    return {
      selectAll: false,
      tableData: [],
      pagination: { current: 1, size: 5, total: 0 },
      query: { keyword: '', paymentStatus: null },
      createVisible: false,
      submitting: false,
      createForm: { paymentOrderNo: '', paymentStatus: 0, paymentType: '', customerId: null, relatedSalesOrder: '', payableAmount: null, writtenOffAmount: null, uId: null, creationDate: '' },
      showDetailDrawer: false,
      currentOrder: null
    }
  },
  created() {
    this.loadData()
  },
  methods: {
    toggleSelectAll() {
      this.tableData.forEach(item => {
        item.selected = this.selectAll;
      });
    },
    updateSelectAll() {
      this.selectAll = this.tableData.every(item => item.selected);
    },
    prevPage() {
      if (this.pagination.current > 1) {
        this.pagination.current--
        this.loadData()
      }
    },
    nextPage() {
      if (this.pagination.current < this.totalPages) {
        this.pagination.current++
        this.loadData()
      }
    },
    goToPage(page) {
      this.pagination.current = page
      this.loadData()
    },
    onPageSizeChange() {
      this.pagination.current = 1
      this.loadData()
    },
    statusClass(status) {
      if (status === '待核销') return 'status-pending';
      if (status === '部分核销') return 'status-partial';
      if (status === '全部核销') return 'status-verified';
      return '';
    },
    fmtMoney(v) {
      if (v === null || v === undefined) return '-'
      const n = Number(v)
      if (Number.isNaN(n)) return '-'
      return n.toFixed(2)
    },
    fmtDateTime(v) {
      if (!v) return '-'
      const d = new Date(v)
      if (Number.isNaN(d.getTime())) return '-'
      const pad = n => String(n).padStart(2, '0')
      return `${d.getFullYear()}-${pad(d.getMonth()+1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`
    },
    fmtStatus(s) {
      if (s === 0) return '待核销'
      if (s === 1) return '部分核销'
      if (s === 2) return '全部核销'
      return '-'
    },
    fmtPaymentType(v) {
      if (v === null || v === undefined || v === '') return '-'
      const code = typeof v === 'string' ? v.trim() : String(v)
      if (code === '0') return '委外付款'
      if (code === '1') return '采购付款'
      if (code === '2') return '其他付款'
      return v
    },
    resetQuery() {
      this.query = { keyword: '', paymentStatus: null }
      this.pagination.current = 1
      this.loadData()
    },
    async loadData() {
      const payload = {
        pageNum: this.pagination.current,
        pageSize: this.pagination.size,
        paymentOrderNo: this.query.keyword || undefined,
        relatedSalesOrder: this.query.keyword || undefined,
        paymentStatus: this.query.paymentStatus
      }
      const res = await paymentOrderPage(payload)
      const data = res && res.data && res.data.data ? res.data.data : res.data
      this.tableData = (data.records || []).map(x => ({ ...x, selected: false }))
      this.pagination.total = Number(data.total || 0)
    },
    openCreate() {
      this.createVisible = true
      this.createForm = { paymentOrderNo: '', paymentStatus: 0, paymentType: '', customerId: null, relatedSalesOrder: '', payableAmount: null, writtenOffAmount: null, uId: null, creationDate: '' }
    },
    async submitCreate() {
      const payload = { ...this.createForm }
      if (!payload.paymentOrderNo) delete payload.paymentOrderNo // 让后端自动生成
      if (!payload.creationDate) delete payload.creationDate
      if (payload.customerId != null && payload.customerId !== '') payload.customerId = Number(payload.customerId)
      if (payload.payableAmount != null) payload.payableAmount = Number(payload.payableAmount)
      if (payload.writtenOffAmount != null) payload.writtenOffAmount = Number(payload.writtenOffAmount)
      if (payload.uId != null && payload.uId !== '') payload.uId = Number(payload.uId); else delete payload.uId
      try {
        this.submitting = true
        await paymentOrderCreate(payload)
        this.createVisible = false
        this.loadData()
      } catch(e) {
        console.error('创建付款单失败', e)
      } finally {
        this.submitting = false
      }
    },
    async viewDetail(row) {
      if (!row || !row.id) return
      try {
        const res = await paymentOrderDetail(row.id)
        const data = res && res.data && res.data.data ? res.data.data : res.data
        this.currentOrder = data || null
        this.showDetailDrawer = !!this.currentOrder
      } catch (e) {
        console.error('获取付款单详情失败', e)
      }
    },
    closeDetailDrawer() {
      this.showDetailDrawer = false
      this.currentOrder = null
    }
  }
}
</script>

<style scoped>
.payment-order {
  padding: 20px;
  background-color: #f5f7fa;
}

.title-section {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
}

.title-section h2 {
    font-size: 20px;
    font-weight: bold;
}

.controls-section {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
  gap: 16px;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  margin-bottom: 20px;
  align-items: center;
}

.filters {
    display: flex;
    flex-wrap: wrap;
    gap: 16px;
    align-items: center;
}

.filter-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.filter-item label {
  font-size: 14px;
  white-space: nowrap;
}

.filter-item input, .filter-item select {
  padding: 8px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  width: 150px;
}

.actions {
  display: flex;
  gap: 10px;
}

.btn-primary {
  background-color: #409eff;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
}

.btn-secondary {
  background-color: #fff;
  color: #606266;
  border: 1px solid #dcdfe6;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
}

.table-section {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
}

table {
  width: 100%;
  border-collapse: collapse;
}

th, td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #ebeef5;
}

th {
  background-color: #f8f9fa;
}

.sortable-header {
  cursor: pointer;
  position: relative;
}

.tooltip {
  position: absolute;
  top: -25px;
  left: 50%;
  transform: translateX(-50%);
  background: #f44336;
  color: white;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  white-space: nowrap;
  opacity: 0;
  transition: opacity 0.2s;
}

.sortable-header:hover .tooltip {
  opacity: 1;
}

.link-style {
    color: #409eff;
    cursor: pointer;
}

.status-pending {
    color: #f56c6c;
    background-color: #fef0f0;
    padding: 4px 8px;
    border-radius: 4px;
}

.status-partial {
    color: #e6a23c;
    background-color: #fdf6ec;
    padding: 4px 8px;
    border-radius: 4px;
}

.status-verified {
    color: #67c23a;
    background-color: #f0f9eb;
    padding: 4px 8px;
    border-radius: 4px;
}

.footer-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
  background-color: #fff;
  padding: 10px 20px;
  border-radius: 8px;
}

.footer-left {
  display: flex;
  align-items: center;
  gap: 8px;
}

.pagination {
  display: flex;
  align-items: center;
  gap: 8px;
}

.pagination button {
  padding: 6px 12px;
  border: 1px solid #dcdfe6;
  background-color: #fff;
  cursor: pointer;
  border-radius: 4px;
}

.pagination button.active {
  background-color: #409eff;
  color: white;
  border-color: #409eff;
}

.pagination select {
  padding: 6px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}

/* 详情抽屉样式（对齐收款单） */
.detail-drawer {
  position: fixed;
  top: 0;
  right: -400px;
  width: 400px;
  height: 100vh;
  background-color: #fff;
  box-shadow: -2px 0 8px rgba(0, 0, 0, 0.1);
  transition: right 0.3s ease;
  z-index: 1000;
  overflow-y: auto;
}

.detail-drawer.show { right: 0; }

.drawer-header {
  padding: 20px;
  border-bottom: 1px solid #ebeef5;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.drawer-header h3 { margin: 0; font-size: 18px; }

.close-btn { background: none; border: none; font-size: 24px; cursor: pointer; color: #909399; }
.close-btn:hover { color: #606266; }

.drawer-content { padding: 20px; }

.detail-section { margin-bottom: 24px; }
.detail-section h4 { margin: 0 0 16px 0; font-size: 16px; color: #303133; border-bottom: 1px solid #ebeef5; padding-bottom: 8px; }
.detail-grid { display: grid; gap: 12px; }
.detail-item { display: flex; align-items: center; }
.detail-item label { min-width: 100px; color: #606266; font-weight: 500; }
.detail-item span { color: #303133; }
.detail-item .amount { font-weight: 600; color: #409eff; }

.drawer-actions { display:flex; justify-content:flex-end; gap:12px; padding: 12px 20px; border-top:1px solid #ebeef5; }

/* 新建模态框样式（对齐收款单） */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1001;
}

.create-modal {
  background-color: #fff;
  border-radius: 8px;
  width: 760px;
  max-height: 80vh;
  overflow-y: auto;
}

.modal-header {
  padding: 16px 20px;
  border-bottom: 1px solid #ebeef5;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: #8ec7ff;
  color: #fff;
  border-radius: 8px 8px 0 0;
}

.modal-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.modal-content { padding: 20px; }

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #fff;
}

.close-btn:hover { color: #eef5ff; }

.form-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px 20px;
  margin-bottom: 24px;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-group label {
  font-weight: 500;
  color: #303133;
}

.form-group input,
.form-group select {
  padding: 8px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  font-size: 14px;
  height: 36px;
}

.form-group input:focus,
.form-group select:focus {
  outline: none;
  border-color: #409eff;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}
</style>

